import logging
import logging.handlers
import os
import time



projectName = "py_autotask"


def mkdir(dirName='/logs'):
    # 创建文件目录 {projectName}}/logs
    project_path = os.path.abspath(os.path.dirname(__file__))
    rootPath = project_path[0:project_path.find(projectName) + projectName.__len__()]
    logs_dir = rootPath + dirName
    if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
        pass
    else:
        os.mkdir(logs_dir)
    return logs_dir


initLog = {}


class Logs(object):

    def __init__(self, name='default'):
        if name not in initLog:
            self.logger = logging.getLogger(name)
            # 设置输出的等级
            # LEVELS = {'NOSET': logging.NOTSET,
            #           'DEBUG': logging.DEBUG,
            #           'INFO': logging.INFO,
            #           'WARNING': logging.WARNING,
            #           'ERROR': logging.ERROR,
            #           'CRITICAL': logging.CRITICAL}
            # 创建/logs目录
            logs_dir = mkdir()
            # 修改log保存位置
            timestamp = time.strftime("%Y-%m-%d", time.localtime())
            logfilename = f'{timestamp}-{name}.txt'
            logfilepath = os.path.join(logs_dir, logfilename)

            # 添加内容到日志句柄中
            rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfilepath,
                                                                       maxBytes=1024 * 1024 * 50,
                                                                       backupCount=5)
            # 设置输出格式
            formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
            rotatingFileHandler.setFormatter(formatter)
            # 控制台句柄
            console = logging.StreamHandler()
            console.setLevel(logging.INFO)
            console.setFormatter(formatter)
            self.logger.addHandler(rotatingFileHandler)
            self.logger.addHandler(console)
            self.logger.setLevel(logging.INFO)
            self.info(f"com.util.logs-{name} init");
            initLog.setdefault(name, self)
        else:
            self.logger = initLog.get(name).logger

    def info(self, message, *args, **kwargs):
        self.logger.info(message, *args, **kwargs)

    def debug(self, message, *args, **kwargs):
        self.logger.debug(message, *args, **kwargs)

    def warning(self, message, *args, **kwargs):
        self.logger.warning(message, *args, **kwargs)

    def error(self, message, *args, **kwargs):
        self.logger.error(message, *args, **kwargs)

    def exception(self, message, *args, **kwargs):
        self.logger.exception(message, *args, **kwargs)
